# get Tkinter
from Tkinter import *
import Tkinter
from SmallLEDSquareDraw import *

#def onLeftClick(event):
#    print 'Got left Mouse button',
#    showPosEvent(event)
    
class LEDGridDraw:

    # __init__: the initializing function
    #       sets up the LEDGridDraw widget
    #       with 15 SmallLEDSquares in formation
    #       with initial names of 1-15, and
    #       initial duty cycles of 0.
    def __init__(self, master,mainmaster):
        
        # set the frames specific to this grid and initialize
        # NOTE: self.main is the frame to put LEDSetting in
        self.master = master
        self.main = mainmaster
        self.mainframe = Frame(self.master, relief=RIDGE, bd=2)
        self.mainframe.grid(column=0,columnspan=3,row=0,rowspan=3)

        # set up inner frames for organization purposes
        self.frame1 = Frame(self.mainframe)
        self.frame2 = Frame(self.mainframe)
        self.frame3 = Frame(self.mainframe)
        self.frame4 = Frame(self.mainframe)
        self.frame5 = Frame(self.mainframe)

        self.frame1.grid(column=0,row=0,padx=5,pady=5)
        self.frame2.grid(column=2,row=0,padx=5,pady=5)
        self.frame3.grid(column=1,row=1,padx=5,pady=5)
        self.frame4.grid(column=0,row=2,padx=5,pady=5)
        self.frame5.grid(column=2,row=2,padx=5,pady=5)

        # set up the array of SmallLEDSquares
        # with the initial names of LED1 through LED15
        # and zero for the duty cycle
        self.array=[]
        for i in range(0,3):
            self.array.append(SmallLEDSquareDraw(self.frame1, self.main, "LED "+str(i+1), 0))
        for i in range(3,6):
            self.array.append(SmallLEDSquareDraw(self.frame2, self.main, "LED "+str(i+1), 0))
        for i in range(6,9):
            self.array.append(SmallLEDSquareDraw(self.frame3, self.main, "LED "+str(i+1), 0))
        for i in range(9,12):
            self.array.append(SmallLEDSquareDraw(self.frame4, self.main, "LED "+str(i+1), 0))
        for i in range(12,15):
            self.array.append(SmallLEDSquareDraw(self.frame5, self.main, "LED "+str(i+1), 0))

        # setting up the LED groupings
        for i in range(0,15,3):
            self.array[i].retSquareFrame().grid(column=1, columnspan=2, row=0, rowspan=2)
        for i in range(1,15,3):
            self.array[i].retSquareFrame().grid(column=0, columnspan=2, row=2, rowspan=2)
        for i in range(2,15,3):
            self.array[i].retSquareFrame().grid(column=2, columnspan=2, row=2, rowspan=2)


    # redrawGrid: replaces the name and setting of
    #       a specific square on the grid,
    #       using the redraw method from SmallLEDSquareDraw
    #   parameters:
    #       self: the required hidden parameter
    #       squareNum: the number in the array of the square to be changed
    #       naming: the name for the square
    #       setting: the setting for the square
    def redrawGrid(self, squareNum, naming, setting):
        # call the function for redrawing the square on the square in the array
        self.array[squareNum].redrawSquare(naming, setting)
        
    # saveGrid
    # This method opens up a file for writing, and places the LED
    # information into it in the following format:
    #
    # LED LABEL,DUTY CYCLE VALUE
    #
    # params: 
    #    outfile - the file where the LED Square data will be stored
    def saveGrid(self, outfile):
        index = 0 # used to iterate through the LED array in the GUI
        
        f = open(outfile, 'w') # open the file with write permissions
        
        while index < len(self.array):
            f.write(self.array[index].getName()) #write the name of the LED to f
            f.write(',')
            f.write(str(self.array[index].getDutyCycle())) #write the duty cycle of the LED to f
            f.write('\n')
            
            index = index + 1
        
        f. close() # close file f
        
    # loadGrid
    # This method opens up a file, infile, and uses the file's info
    # to set all the LEDs to the specified name and duty cycle value. 
    #
    # params: 
    #    infile - the file to read data from
    def loadGrid(self, infile):
        index = 0 # used to iterate through the LED array in the GUI
        f = open(infile, 'r') # open the file with read permissions
        
        try:
            with open(infile) as f:
                for line in f:   
                    line.strip() # clear out leading/trailing whitespace
                    words = line.split(',')
                    
                    self.array[index].setName(words[0]) #get LED name
                    self.array[index].setDutyCycle(int(words[1])) #get duty cycle
                    
                    index = index + 1
                      
        except IOError as e: #if the file could not be read from
            print 'Operation failed: %s' % e.strerror
            
        f.close() # close file f
        
    def clearValues(self):
        """This function sets all of the LED duty cycles in the GUI to 0 and renames them
           LED1 through LED15"""

        index = 0 # used to iterate through the LED array in the GUI
        
        while index < len(self.array):
            self.array[index].setName("LED " + str(index + 1))
            self.array[index].setDutyCycle(0)
            
            index = index + 1
        

    # retGridFrame: returns the frame containing the whole grid,
    #       so as to allow for packing on upper levels
    #   return: the main frame
    def retGridFrame(self):
        return self.mainframe

    def loadPreset (self, color):
        """This function sets the duty cycles of each LED on the 
           grid based on what preset is selected"""

        #array positions in GUI led grid representation
        redpositions = [0,3,6,9,12]
        greenpositions = [2,5,8,11,14]
        bluepositions = [1,4,7,10,13]

        #display LED color names on GUI
        for redpos in redpositions:
            self.array[redpos].setName("Red")
        for greenpos in greenpositions:
            self.array[greenpos].setName("Green")
        for bluepos in bluepositions:
            self.array[bluepos].setName("Blue")
           
        #set duty cycle display for each LED depending on what preset is selected
        if (color == "Red"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(255)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(0)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(0)
        elif (color == "Orange"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(255)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(165)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(0)
        elif (color == "Yellow"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(255)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(255)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(0)
        elif (color == "Green"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(0)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(255)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(0)
        elif (color == "Blue"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(0)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(0)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(255)
        elif (color == "Indigo"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(75)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(0)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(130)
        elif (color == "Violet"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(128)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(0)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(128)
        elif (color == "White"):
            for redpos in redpositions:
                self.array[redpos].setDutyCycle(255)
            for greenpos in greenpositions:
                self.array[greenpos].setDutyCycle(255)
            for bluepos in bluepositions:
                self.array[bluepos].setDutyCycle(255)
        else:
            pass

